var app = getApp();
import { api, util, dialog} from '../../../../js/util'
import {
  router,pagesInfo
} from '../../../../js/router';
import { orderdetail, orderlist, fee, fastorder, order } from "../../../../js/modules/order.js"
import {upload} from '../../../../js/modules/material.js'
import { $ecCountDown } from '../../../../components/index'
import {
  wholesaleSettings 
} from "../../../../js/modules/gloab"; 
import authorize from '../../../../js/modules/authorize.js'
import BasePage from '../../../../js/common/base-page'
import {
  profile
} from "../../../../js/modules/store.js";
import {list} from '../../../../js/modules/mall';
import { setStorageSync } from '../../../../js/compatible';
import { isEmpty, alert } from '../../../../js/newUtil';
BasePage({
  pageKey:"orderDetail",
  validateLogin: false,
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    OrderInfo: {},
    OrderItem: [],
    Consignee: [],
    InvoiceInfo: [],
    DispatchInfo: [],
    IsHasInvoice: true,
    IsHasDispatch: true,
    noPayMoney: 0.00,
    batchShow: false,
    tableShow: false,
    invoiceShow: false,
    infoShow: false,
    consignee:{},
    payway: {
      list: [],
      array: [],
      index: 0
    },
    voucher: [],
    signIn:[],//签收凭证
    attachmentList:[],
    freightMode:1,//运费模式
    quantityDigits:2,//数量显示位数
    priceDigits:2, //价格显示位数
    decimalDigits: 2,//金额小数位数
    openComment:false,//是否显示评价
    headerBg:"",
    showPosterShadow: false, //海报弹层
    saveBtn: false,//保存图片按钮
    downlogo: "",
    logo: "",
    isIphoneX:app.globalData.isIphoneX,
    Initiator:0,
    Currency:'',//货币符号
    isView:false,
    SiteName:'',
    virtualImageList:[],
    CloseBuyerCancel:false,//禁止买家取消订单
    retreatList:[],//列表
    configLoaded: false, // config数据是否获取完成
    bottomButtonList: [], // 底部按钮列表
    bottomMore: false, // 是否显示底部按钮区更多内容
    selfPickCodeText: [], // 自提点提货码
    c0: true, // 是否不显示支付倒计时，没有支付倒计时时间时或超过可支付时间时不显示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();//隐藏分享
    var oddNumber = decodeURIComponent(options.oddNumber);
    console.log(oddNumber,options.view)
    this.setData({
      isView: options.view == 1
    })
    this.data.oddNumber=oddNumber;
    this.getWholesaleConfig();
    this.cancelOrder = this.selectComponent("#cancelOrder");
  },

  /**
   * 倒计时
   *  */
  setCountdown(time) {
    // console.log("x-time",time);
    this.c1 = new $ecCountDown({
      date: time,
      render(date) {
        // console.log("x-date",date.sec);
        const days = this.leadingZeros(date.days, 2)
        const hours = this.leadingZeros(date.hours, 2)
        const min = this.leadingZeros(date.min, 2)
        const sec = this.leadingZeros(date.sec, 2)

        this.setData({
          c1: days,
          c2: hours,
          c3: min,
          c4: sec,
          c0: (date.days == 0 && date.hours == 0 && date.min == 0 && date.sec <= 0) || (isNaN(date.days) || isNaN(date.hours) || isNaN(date.min)||isNaN(date.sec))
        })
      },
    });
  },
  /**加载订单信息 */
  getDetail: function (oddNumber) {
    var that = this;
    orderdetail.getDetail(oddNumber, that.data.isView, function (orderInfo, orderItem, consignee){
      var noPayMoney = parseFloat(orderInfo.Payables) - parseFloat(orderInfo.PaidMoney);
      var orderId = orderInfo.Id, voucher=[],signIn=[];
      if (orderInfo.Credentials.length>0){
        voucher = orderInfo.Credentials.split(',');
        for (var i = 0; i < voucher.length;i++){
          voucher[i] = that.data.imgDomain+voucher[i];
        }
      }
      if(orderInfo.SignPicture){
        signIn = orderInfo.SignPicture.split(',');
        for (var i = 0; i < signIn.length;i++){
          signIn[i] = that.data.imgDomain+signIn[i];
        }
      }
      orderInfo.BuyRemark=orderInfo.BuyRemark.replace(/()+/ig, "\n")
      
      if(orderInfo.CustomizeFields){
        var CustomizeFields = orderInfo.CustomizeFields;
        for(var i = 0;i<CustomizeFields.length;i++){
          if(CustomizeFields[i].FieldType == 'image'){
            if(CustomizeFields[i].ChooseValue){
              CustomizeFields[i].ChooseValue = CustomizeFields[i].ChooseValue.split(',');
            }
          }
        }
      }
      // console.log(orderInfo.CustomizeFields,'==========orderInfo.CustomizeFields');
      that.setData({
        OrderInfo: orderInfo,
        OrderItem: orderInfo.children,
        noPayMoney: noPayMoney.toFixed(2),
        voucher: voucher,
        signIn:signIn,
        consignee: {
          Province: orderInfo.Province,
          City:orderInfo.City,
          Area:orderInfo.Area,
          Address:orderInfo.Address,
          Mobile:orderInfo.Mobile,
          Name:orderInfo.RealName,
          Town: orderInfo.Town,
          AddressId:0
        },
        Initiator:authorize.getEntity() ? authorize.getEntity().manager.Initiator:0
      });
      that.setFile()
      //如果待支付时，显示倒计时
      if ((orderInfo.PayStatus == 0 || orderInfo.PayStatus == 3) && orderInfo.PayTypeId != 1 && orderInfo.PayTypeId != 5 && orderInfo.Status != 3 && orderInfo.Status != 8 && orderInfo.Status > 0){
        orderdetail.getPayEndTime(orderId,function(time){
          that.setCountdown(time);
        });
      }
      that.getDispatchInfo(orderId);
      that.getInvoiceInfo(orderId);
      that.retreatinfo(orderId);
      that.getPayTypes(that);
      var img_list=[];
      orderInfo.attachmentTable.map(function(item){
        img_list.push(that.data.imgDomain+item.Url);
      })
      that.setData({
        attachmentList: img_list
      });
      if (orderInfo.Status == 0){
        that.calFreight();
      }
      that.setData({
        richtext_content: orderInfo.DiscountDesc
      })
      that.setBottomButton()
    });
  },
  /**
   * 设置底部导航显示的按钮
   */
  setBottomButton: async function () {
    let that = this
    let waitForConfigLoad = function () {
      return new Promise((resolve) => {
        if (that.data.configLoaded) {
          clearInterval(that.configInterval)
          resolve()
          return
        }
        const TIMEOUT = 10000
        const STEP = 500
        let time = 0
        that.configInterval = setInterval(() => {
          if (that.data.configLoaded || time > TIMEOUT) {
            clearInterval(that.configInterval)
            resolve()
            return
          }
          time += STEP
        }, STEP)
      })
    }
    await waitForConfigLoad()
    let bottomButtonList = []
    let {
      isView,
      OrderInfo,
      CloseBuyerCancel,
      openComment,
      Initiator
    } = this.data
    if ((!CloseBuyerCancel || (CloseBuyerCancel && OrderInfo.Status == 7)) && OrderInfo.RetreatCount != OrderInfo.ProductNum && OrderInfo.CancelStatus == 1 && OrderInfo.IsRetreatAuthor == 1 && (OrderInfo.PayStatus == 1 || OrderInfo.Status > 5) && OrderInfo.Status != 8) {
      bottomButtonList.push({
        text: '申请售后',
        method: 'onApplyRetreatEvent'
      })
    }
    if (!isView && openComment && OrderInfo.Status == 7 && OrderInfo.IsComment == 0) {
      bottomButtonList.push({
        text: '立即评价',
        method: 'onCommentEvent'
      })
    }
    if (!isView && OrderInfo.Status == 8 && OrderInfo.PayStatus == 0) {
      bottomButtonList.push({
        text: '删除订单',
        method: 'onDeleteEvent'
      })
    }
    if (!isView && OrderInfo.Status < 6 && OrderInfo.PayStatus != 2 && OrderInfo.PayStatus != 3  && OrderInfo.CancelStatus == 1) {
      if (CloseBuyerCancel ? (OrderInfo.Status < 5||(OrderInfo.Status == 5 && OrderInfo.PayStatus == 0 && OrderInfo.PayTypeId == 2)) : (OrderInfo.Status != 5 || (OrderInfo.Status == 5 && OrderInfo.RetreatCount == 0))) {
        bottomButtonList.push({
          text: '取消订单',
          method: 'showModal'
        })
      }
    }
    if (!isView && OrderInfo.Status >=5 && OrderInfo.Status!=8 && OrderInfo.ContractUrl) {
      bottomButtonList.push({
        text: '下载合同',
        method: 'bindContract'
      })
    }
    if (!isView && OrderInfo.Status==0 && Initiator==1) {
      bottomButtonList.push({
        text: '提交订单',
        method: 'submitOrder'
      })
    }
    if (!isView && OrderInfo.Status == 7||OrderInfo.Status==8) {
      bottomButtonList.push({
        text: '再次购买',
        method: 'onAginBuyEvent'
      })
    }
    if (!isView && OrderInfo.Status == 6) {
      bottomButtonList.push({
        text: '立即收货',
        method: 'onConfirmReceiveEvent'
      })
    }
    if (!isView && OrderInfo.Status == 10) {
      bottomButtonList.push({
        text: '部分收货',
        method: 'onConfirmReceiveEvent',
      })
    }
    if (OrderInfo.Status > 0 && OrderInfo.Status != 8 && OrderInfo.PayStatus != 1) {
      bottomButtonList.push({
        text: '立即付款',
        method: 'onPayEvent'
      })
    }
    let highlightList = ['submitOrder', 'onAginBuyEvent', 'onPayEvent']
    if (bottomButtonList.length > 0) {
      let last = bottomButtonList[bottomButtonList.length - 1]
      if (highlightList.includes(last.method)) {
        bottomButtonList[bottomButtonList.length - 1].highlight = true
      }
    }
    console.log('底部菜单栏')
    this.setData({
      bottomButtonList
    })
  },
  /**
   * 点击底部按钮
   * @param {*} e 
   */
  tapBottomButton (e) {
    let method = e.currentTarget.dataset.method
    let OrderInfo = this.data.OrderInfo || {}
    let orderid = OrderInfo.Id || ''
    let oddnumber = OrderInfo.OddNumber || ''
    let url = OrderInfo.ContractUrl || ''
    e.currentTarget.dataset = {
      orderid,
      oddnumber,
      url
    }
    this[method](e)
  },
  /**
   * 点击底部更多
   */
  showBottomMore () {
    this.setData({
      bottomMore: !this.data.bottomMore
    })
  },
  /**
   * 获得订单发货信息 
   * */
  getDispatchInfo: function (orderId) {
    var that = this;
    orderdetail.getDispatchInfo(orderId,function(content){
      if (content.length > 0) {
        let selfPickCodeText = [] // 提货码
        content.map((item,index)=>{
          if(item.Voucher){
            let list = [];
            item.Voucher.split(',').map((src)=>{
              list.push(that.data.imgDomain+src);
            })
            item.Voucher = list
          }
          if (item.CodeText) { // 提货码
            selfPickCodeText.push(item.CodeText)
          }
        })
        that.setData({
          DispatchInfo: content,
          selfPickCodeText
        });
      } else {
        that.setData({
          IsHasDispatch: false
        });
      }
    });
  },
  /**
   * 获得订单发票信息 
   * */
  getInvoiceInfo: function (orderId) {
    var that = this;
    orderdetail.getInvoiceInfo(orderId,
      function (content) {
        if (content && content.length > 0) {
          that.setData({
            IsHasInvoice: true,
            InvoiceInfo: content[0]
          });
        } else {
          that.setData({
            IsHasInvoice: false
          });
        }
      });
  },
  /**
 * 获取支付方式
 */
  getPayTypes(that) {
    if (that.data.OrderInfo.Status != 0) return;
    orderdetail.getPaymentType(function (content) {
      var arr = [], list = [];
      for (var i = 0; i < content.length; i++) {
        arr.push(content[i].TypeName);
        list.push(content[i]);
      }
      that.setData({
        "payway.list": list,
        "payway.array": arr
      });
    });
  },
  /**
   * 去商品清单
   */
  goGoodsList:function(){
    router.navigate({
      path:'orderGoodsList',
      params:{}
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      headerBg:api.titleColor||"#e56b14",
      mainColor: api.titleColor||"#e56b14",
      Currency:api.Currency || '￥'
    })
    this.wxConfirmReceiveEvent()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    setStorageSync('tabindex', app.dns.centerNum);
    router.navigate({
      path: "center"
    });
    clearInterval(this.configInterval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /**
   * 点击查看发货信息
   */
  showBatch: function () {
    this.setData({
      batchShow: !this.data.batchShow
    })
  },
  /**
   * 点击查看退换货信息
   */
  showTable: function () {
    this.setData({
      tableShow: !this.data.tableShow
    })
  },
  /**
   * 点击查看发票信息
   */
  showInvoice: function () {
    this.setData({
      invoiceShow: !this.data.invoiceShow
    })
  },
  /**
   * 点击查看更多详情
   */
  showInfo() {
    this.setData({
      infoShow: !this.data.infoShow
    })
  },
  // 导航
  bindOpenNav:function(e){
    var item = e.currentTarget.dataset.item;
    wx.openLocation({        
      latitude: item.PointLatitude,  
      longitude: item.PointLongitude,
      name: item.PointName,
      address: item.PointAddress,
      scale: 28
    });
  },
  /**
   * 转账汇款凭证
   */
  bindUploadEvent:function(e){
    let that = this
    let fileList = e.detail.fileList || []
    let image_list = fileList.map(item => {
      return item.src
    })
    orderdetail.upload_voucher(that.data.OrderInfo.Id, image_list.join(","),function(){
      that.data.OrderInfo.Credentials = image_list.join(",");
      let voucher=[];
      image_list.map((item)=>{
        voucher.push(that.data.imgDomain + item);
      });
      that.setData({  
        OrderInfo: that.data.OrderInfo,
        voucher: voucher
      });
    });
  },
  setFile () {
    let OrderInfo = this.data.OrderInfo || {}
    let uploadFile = this.selectComponent('#uploadFile')
    let signPicture = this.selectComponent('#signPicture')
    let credentials = this.selectComponent('#credentials')
    let attachmentTable = OrderInfo.attachmentTable || []
    uploadFile.setList(attachmentTable)
    if (OrderInfo.Credentials && credentials) {
      let arr = OrderInfo.Credentials.split(',')
      arr = arr.map((item) => {
        return {
          src: item,
          type: 'image'
        }
      })
      credentials.setList(arr)
    }
    if (OrderInfo.SignPicture && signPicture) {
      let arr = OrderInfo.SignPicture.split(',')
      arr = arr.map((item) => {
        return {
          src: item,
          type: 'image'
        }
      })
      signPicture.setList(arr)
    }
  },
  /**
   * 附件
   */
  bindUploadAdjunct:function(e){
    var that = this;
    let imgDomain = this.data.imgDomain
    let attachmentList = this.data.attachmentList || []
    let fileList = e.detail.fileList || []
    let list1 = []
    let list2 = []
    for (let i = 0; i < fileList.length; i++) {
      let src = fileList[i].src
      if (/^\/\//.test(src)) {
        src = src.slice(1)
      }
      src = imgDomain + src
      let find = false
      src = src.replace('http://', '')
      src = src.replace('https://', '')
      for (let j = 0; j < attachmentList.length; j++) {
        let src1 = attachmentList[j]
        src1 = src1.replace('http://', '')
        src1 = src1.replace('https://', '')
        if (src == src1) {
          list1.push(fileList[i])
          find = true
          break
        }
      }
      if (!find) {
        list2.push(fileList[i])
      }
    }
    console.log('要上传的数据:', list2)
    let file = list2.map((item) => {
      let src = item.src
      if (/^\/\//.test(src)) {
        src = src.slice(1)
      }
      src = imgDomain + src
      return src
    })
    let data = ''
    for (let k = 0; k < list2.length; k++) {
      data += `
        <attachment>
          <name><![CDATA[${list2[k].name || '附件文件'}]]></name>
          <url>${list2[k].src}</url>
        </attachment>
      `
    }
    orderdetail.upload_adjunct(that.data.OrderInfo.Id, data,function(){
      list2.map(function (item) {
        that.data.virtualImageList.push(item.src);
      });
      attachmentList = [...attachmentList, ...file]
      that.setData({
        attachmentList
      })
    });
  },
  /**
   * 删除
   */
  onDelImageEvent:function(e){
    var that = this;
    var imgidx = e.currentTarget.dataset.imgidx;
    var image_list = that.data.signIn;
    image_list.splice(imgidx, 1);
    that.data.OrderInfo.SignPicture = '';
    that.setData({
      signIn: image_list,
      OrderInfo: that.data.OrderInfo
    })
  },
  /**
   * 签收凭证
   */
  bindUploadSign:function(e){
    let that = this
    let fileList = e.detail.fileList || []
    let image_list = fileList.map(item => {
      return item.src
    })
    orderdetail.upload_sign(that.data.OrderInfo.Id, image_list.join(","),function(){
      that.data.OrderInfo.SignPicture = image_list.join(",");
      let signIn=[];
      image_list.map((item)=>{
        signIn.push(that.data.imgDomain + item);
      });
      that.setData({
        OrderInfo: that.data.OrderInfo,
        signIn: signIn
      });
    })
  },
  /**
   * 删除
   */
  onDelImageEvent:function(e){
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    var that = this;
    var imgidx = e.currentTarget.dataset.imgidx;
    var image_list = that.data.signIn;
    image_list.splice(imgidx, 1);
    that.data.OrderInfo.SignPicture = '';
    that.setData({
      signIn: image_list,
      OrderInfo: that.data.OrderInfo
    })
  },
  /**
   * 点击查看凭证大图
   */
  showbigImg: function (event) {
    var that = this;
    var index = event.currentTarget.dataset.index;
    var srcs = event.currentTarget.dataset.srcs;
    var type = event.currentTarget.dataset.type;
    if(type == 1){
      for(var i=0;i<srcs.length;i++){
        srcs[i] = that.data.imgDomain + srcs[i]
      }
    }
    //图片预览
    wx.previewImage({
      current: srcs[index], // 当前显示图片的http链接
      urls: srcs // 需要预览的图片http链接列表
    })
  },
  /**
 * 地址选择
 */
  goAddr: function () {
    router.navigate({
      path: "addressList",
      params: {
        id: 0
      }
    });
  },
  onChangePayWay:function(e){
    var current = this.data.payway.list[e.detail.value];
    this.data.OrderInfo.PayTypeId = current.Id;
    this.setData({
      OrderInfo: this.data.OrderInfo,
      "payway.index": e.detail.value
    });
  },

  /**
   * 计算运费 
   * 
  */
  calFreight() {
    let that = this;
    let { consignee, freightMode } = this.data;
    let orderInfo = this.data.OrderInfo;
    let addressId = consignee.AddressId || '';
    let param = {
      Weight: orderInfo.Weight,
      AddressId: addressId,
      FreightMode: freightMode,
      FreeFreight: orderInfo.FreeFreight,
      SupplierId: orderInfo.FKId
    };
    fee.calFreight(param, function (freight) {
      orderInfo.Freight = parseFloat(freight);
      that.calPayablesAmount();
    });

  },
    /**
       * 计算支付价格 
       * 
       */
  calPayablesAmount() {
    let orderInfo = this.data.OrderInfo;

    let params = {
      Freight: orderInfo.Freight, //运费
      Taxes: orderInfo.Taxes, //税费
      ProductAmount: orderInfo.ProductAmount, //货品总金额 
      CouponDiscount: orderInfo.CouponDiscount, //优惠劵优惠金额
      PayDiscount: 0, //支付优惠金额
      DiscountAmount: orderInfo.OrderDiscount, //进货车优惠金额   
      DeductionTotal: 0, //积分抵扣的金额
      useGrade: orderInfo.PayableIntegral
    }

    let retPayables = fee.calPayables(params);
    orderInfo.Payables = retPayables;
    this.setData({
      OrderInfo: orderInfo
    });
  },
  /**
   * 提交
   */
  submitOrder:function(){
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    let that=this;
    let orderInfo = this.data.OrderInfo;
    util.confirm(function () {
    let data={
      OrderId: orderInfo.Id,
      AddressId: that.data.consignee.AddressId,
      PayTypeId: orderInfo.PayTypeId
    }
    orderdetail.submitOrder(data,function(){
      that.getDetail(orderInfo.OddNumber);
    });
    }, null, "是否确认提交订单？", "确认提交")
  },
  /**
   * 删除订单
   * @param {*} e 
   */
  onDeleteEvent: function (e) {
    var that = this
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store')
      return
    }
    let orderInfo = this.data.OrderInfo
    var id = orderInfo.Id
    orderlist.deleteOrder(id, function () {
      wx.navigateBack()
    })
  },
  /**
  * 立即收货
  */
  onConfirmReceiveEvent: function (e) {
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    var that = this;
    var orderid = e.currentTarget.dataset.orderid;
    var oddnumber = e.currentTarget.dataset.oddnumber;
    let OrderInfo = this.data.OrderInfo || {}
    // 调用微信收货组件
    if (!isEmpty(OrderInfo.WxExtraData) && wx.openBusinessView) {
      order.getWxShippingInfo(orderid, function (res) {
        if (res.Success == false) {
          // 同步订单失败时,调用收货原逻辑
          // 比如用户已经在微信消息中确认收货了,就会同步失败
          orderlist.confirmReceive(oddnumber, function () {
            that.getDetail(oddnumber);
          });
          return
        }
        let extraData = OrderInfo.WxExtraData || {}
        wx.openBusinessView({
          businessType: "weappOrderConfirm",
          extraData: {
            transaction_id: extraData.TransactionId,
            merchant_id: extraData.MerchantId,
            merchant_trade_no: extraData.MerchantTradeNo,
            orderid,
            oddnumber
          },
          success (res) {
            console.log('weappOrderConfirm success', res)
          },
          fail (err) {
            console.log('weappOrderConfirm fail', err)
          }
        })
      })
      return
    }
    orderlist.confirmReceive(oddnumber, function () {
      that.getDetail(oddnumber);
    });
  },
    /**
   * 判断是否为微信确认收货组件,成功点击收货
   * 处理完相关逻辑后刷新页面
   */
  wxConfirmReceiveEvent() {
    let that = this
    let OrderInfo = this.data.OrderInfo || {}
    if (!isEmpty(app.globalData.appShowData)) {
      let e = app.globalData.appShowData || {}
      // 场景值1038,从其他小程序返回(确认收货组件会使用navigateBackMiniProgram返回当前小程序)
      // 通过 app onshow中的参数来处理逻辑
      if (e.scene == 1038 && e.referrerInfo) {
        let referrerInfo = e.referrerInfo || {}
        let extraData = referrerInfo.extraData || {}
        let appId = referrerInfo.appId
        let status = extraData.status
        if (!isEmpty(extraData) && !isEmpty(OrderInfo)) {
          // 当用户确认收货时 status 为success
          if (status != 'success') {
            that.refreshPage()
            return
          }
          let reqData = extraData.req_extradata || {}
          let oddnumber = reqData.oddnumber || '' // 订单信息
          let receiveOrderHistory = app.globalData.receiveOrderHistory || [] // 已经调用过确认收货的订单
          // 当已经调用过确认收货,则不再次调用
          if (oddnumber && !receiveOrderHistory.includes(oddnumber)) {
            orderlist.receiveNow(oddnumber, function () {
              app.globalData.receiveOrderHistory.push(oddnumber)
              that.refreshPage()
            })
            return
          }
          that.refreshPage()
          return
        }
        that.refreshPage()
        return
      }
      that.refreshPage()
      return
    }
    this.refreshPage()
  },

  /*
  再次购买
   */
  onAginBuyEvent: function (e) {
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    var id = e.currentTarget.dataset.orderid;
    fastorder.aginBuy(id);
  },

  /**
   * 立即付款
   */
  onPayEvent: function (e) {
    var id = e.currentTarget.dataset.orderid;
    orderlist.onPay(id);
  },
  /**
   * 立即评价
   */
  onCommentEvent: function (e) {
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    var that = this;
    var oddnumber = e.currentTarget.dataset.oddnumber;
    //跳转到退换页面
    router.navigate({
      path: "comment",
      params: {
        oddNumber: oddnumber,
        pageParams: util.base64_encode("?oddNumber="+oddnumber)
      }
    });
  },
  /**
   * 刷新页面
   */
  refreshPage(){
    this.getDetail(this.data.oddNumber);
  },
  /**
   * 申请售后
   */
  onApplyRetreatEvent: function (e) {
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    var orderid = e.currentTarget.dataset.orderid;
    //跳转到退换页面
    router.navigate({
      path: "applyRetreat",
      params: {
        oddNumber: orderid
      }
    });
  },
  /**
 * 展开遮罩层
 */
  showModal: function (e) {
    //判断是否登录
    if (!authorize.isLogin('store')) {
      authorize.redirect('store');
      return;
    }
    var id = e.currentTarget.dataset.orderid;
    this.cancelOrder.showModal(e, id);
  },
  onCancelOrderEvent(){
    this.getDetail(this.data.oddNumber);
  },
  /**
 * 是否允许登记
 */
  /**加载配置项参数 */
  getWholesaleConfig() {
    let that = this;
    let config = wholesaleSettings.getConfig();
    that.setData({
      quantityDigits: config.quantityDigits,
      priceDigits: config.priceDigits,
      freightMode: config.freightMode,
      openComment: config.openComment,
      decimalDigits: config.decimalDigits,
      SiteName: config.SiteName
    });
    var fkid = app.dns.proprietorId;
    var fkflag = app.dns.proprietor;
    list.getWholesaleConfigs(
      fkid,
      fkflag,
      (content)=> {
        that.setData({
          CloseBuyerCancel:content.CloseBuyerCancel,
          logo: content.LogoForMobile,
          configLoaded: true
        });
      })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    // this.data.oddNumber
    if(res.from === 'button'){
      // console.log(res.target);
    }
    var that = this;
    var title = '我在'+that.data.SiteName+'上下了一个订单，赶快来看看吧'
    let path = pagesInfo.SureOrderDetail.url + `?oddNumber=${that.data.oddNumber}&view=1`;
    // console.log(path,'----------lll');
    // todo: 图片调为5:4
    return {
      title: title,
      imageUrl: that.data.OrderItem[0].DefaultPic?that.data.imgDomain+that.data.OrderItem[0].DefaultPic:'/assets/images/img.png',
      path: path
    }
  },
  /**
  * 分享
  */
  btnShare:function(e){
    var that = this;
    dialog.showModal(that, 'showModalStatus')
  },
  /**
   * 隐藏遮罩层
   */
  hideModal: function () {
    dialog.hideModal(this, 'showModalStatus')
  },
  /**
   * 显示海报
   */
  showPoster: function () {
    dialog.hideModal(this, 'showModalStatus')
    this.drawPicture();
    this.setData({
      showPosterShadow: true
    })
  },
  /**
   * 关闭海报
   */
  hidePoster: function () {
    this.setData({
      showPosterShadow: false,
      saveBtn: false
    })
  },
  //绘制海报
  drawPicture: function () {
    let that = this;
    //获取设备信息高度。计算出其他的高度等
    wx.getSystemInfo({
      success: function (res) {
        //调整海报清晰度
        that.setData({
          windowWidth: res.windowWidth * 2,
          windowHeight: res.windowHeight * 2,
          canvasId: "canvas"
        });
        res.windowWidth = res.windowWidth * 2;
        res.windowHeight = res.windowHeight * 2;
        that.initData(res);
      }
    });
  },
  initData: function (res) {
    let that = this;
    that.setData({
      normalPageX:
        (res.windowWidth * 0.74 - res.windowWidth * 0.67) / 2, //左边文本图片X轴位置
      boxWidth: res.windowWidth * 0.74, //分享图片box宽度
      boxheight: res.windowWidth * (0.222 + 0.72 + 0.192) + 20, //分享图片box高度
      boxPageY: 0, //boxY轴位置
      // imgWidth: res.windowWidth * 0.67, //商品图片宽度
      // imgHeight: res.windowWidth * 0.92, //商品图片高度
      // imgPageY: res.windowWidth * 0.15, //商品图片Y轴位置
      codeWidth: res.windowWidth * 0.50, //小程序码图片宽度
      codeHeight: res.windowWidth * 0.50, //小程序码图片高度
      codePageY:res.windowWidth * 0.15, //小程序码Y轴位置

      pricePageY:res.windowWidth * 0.85 + 30 , //价格Y轴位置
      titlePageY:res.windowWidth * 0.85 + 70, //标题Y轴位置
      subTitlePageY:res.windowWidth, //副标题Y轴位置
      contentTitle: that.data.SiteName,
      subTitle:'我在'+that.data.SiteName+'上下了一个订单，赶快来看看吧',
      // market:'llllll',
      price: that.data.OrderInfo.Payables,
      logoWidth: res.windowWidth * 0.05 * 5.5,
      logoHeight: res.windowWidth * 0.05,
    });
    if (that.data.logo != "" && that.data.downlogo == "") {
      wx.downloadFile({
        url: that.data.imgDomain.replace("http://","https://") + that.data.logo,
        success: function (res) {
          that.setData({
            downlogo: res.tempFilePath
          });
        },
        fail: function (err) {
          util.tips(err.errMsg);
          console.log(err.errMsg,'====1');
         }
      });
    }
    that.downloadSkuQrCode();
  },
  //下载小程序码
  downloadSkuQrCode: function () { 
    let that = this;
    const currentRoute = that.getCurrentPageUrlWithArgs();
    profile.load_wx_qrcode(currentRoute, function (content) {
      if (content != "") {
        var url = "data:image/png;base64," + content;
        that.setData({
          preQR: url
        })
        util.base64src(url, function (res) {
          url = res;
          that.setData({
            qrCode: url
          });
          that.createNewImg();
        });
        // console.log(that.data.preQR,'----qr');
      } else {
        that.setData({
          showPosterShadow: false
        }, function () {
          util.tips("未能生成小程序码");
          return;
        })
      }
    });
  },
  getCurrentPageUrlWithArgs: function () {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = options.oddNumber;
    console.log(urlWithArgs,'---urlWithArgs--');
    return {
      url,
      urlWithArgs
    }
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    wx.previewImage({
      urls: [that.data.tempFilePath],
    });
    wx.saveImageToPhotosAlbum({
      filePath: that.data.tempFilePath,
      success(res) {
        wx.hideLoading();
        // utils.aiCardActionRecord(19);
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) { }
          },
          fail: function (res) { }
        })
      },
      fail: function (res) {
        wx.hideLoading();
        wx.showToast({
          title: "保存失败",
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 根据文字多少动态计算高度，然后依次画出矩形，文字，横线和小程序码。
  createNewImg: function () {
    let that = this;
    let ctx = wx.createCanvasContext(that.data.canvasId);
    let contentHeight = that.data.boxheight;
    that.drawSquare(ctx, contentHeight);
    that.setData({
      contentHeight: contentHeight
    });
    //商城logo
    // console.log(that.data.downlogo,'----logo');
    // ctx.drawImage(
    //   that.data.downlogo,
    //   (that.data.boxWidth - that.data.logoWidth) / 2-10,
    //   that.data.logoHeight+20,
    //   200,
    //   60
    // );
    ctx.drawImage(that.data.downlogo, (that.data.boxWidth - that.data.logoWidth) / 2+10,that.data.logoHeight+20, 120, 70)
    console.log(that.data.logoHeight,'----logo',that.data.logoHeight);
    ctx.setFillStyle("#000");
    ctx.font = "normal normal 24px sans-serif";
    ctx.textAlign = "center";
    ctx.fillText(that.data.contentTitle, that.data.logoWidth+40, that.data.logoHeight+120);
    ctx.font = "normal normal 20px sans-serif";
    ctx.fillText(that.data.subTitle, that.data.logoWidth+46, that.data.logoHeight+150);

    ctx.setFillStyle("#666");
    ctx.font = "normal normal 20px sans-serif";
    ctx.textAlign = "left";
    ctx.fillText("订单编号："+that.data.OrderInfo.OddNumber, that.data.normalPageX, that.data.pricePageY+40);
    ctx.fillText("商品种类："+that.data.OrderItem.length+ " 数量："+that.data.OrderInfo.ProductNum, that.data.normalPageX, that.data.pricePageY+80);
    ctx.fillText("订单金额：", that.data.normalPageX, that.data.pricePageY+130);
    // 填充价格符号￥
    ctx.setFillStyle("#cb4255");
    ctx.font = "normal normal 28px sans-serif";
    ctx.fillText(that.data.Currency, that.data.normalPageX + 98, that.data.pricePageY+130);
    // 填充价格文字
    ctx.font = "normal normal 28px sans-serif";
    ctx.fillText(
      that.data.OrderInfo.Payables + that.data.OrderInfo.PayableIntegral?that.data.OrderInfo.PayableIntegral:'',
      that.data.normalPageX + 125,
      that.data.pricePageY+130
    );
    // 计算价格符号￥ + 价格文字宽度
    let priceWidth = ctx.measureText(that.data.Currency + that.data.OrderInfo.Payables + that.data.OrderInfo.PayableIntegral?that.data.OrderInfo.PayableIntegral:'').width;
    //有划线价，才展示
    if (this.data.delPrice) {
      // 填充划线价文字
      ctx.setFillStyle("#999");
      ctx.font = "normal normal 26px sans-serif";
      ctx.fillText(
        that.data.delPrice,
        that.data.normalPageX + priceWidth,
        that.data.pricePageY
      );
      // 计算划线价宽度
      let delPriceWidth = ctx.measureText(that.data.delPrice).width;
      // 填充划线价横线
      ctx.beginPath();
      ctx.moveTo(
        that.data.normalPageX + priceWidth + 2,
        that.data.pricePageY - 4
      );
      ctx.lineTo(
        that.data.normalPageX + priceWidth + delPriceWidth + 2,
        that.data.pricePageY - 4
      );
      ctx.setStrokeStyle("#999");
      ctx.stroke();
      ctx.closePath();
    }
    // 填充小程序码
    ctx.drawImage(
      that.data.qrCode,
      that.data.normalPageX+50,
      that.data.codePageY+110,
      that.data.codeWidth,
      that.data.codeWidth
      // that.data.codeHeight
    );
    // 填充长按立即购买文本
    ctx.setFillStyle("#333");
    ctx.font = "normal normal 18px sans-serif";
    ctx.fillText(
      "扫描/长按识别",that.data.logoWidth,that.data.codePageY + that.data.codeWidth + 140
    );
    ctx.draw(false, function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          that.setData({
            tempFilePath,
            saveBtn: true
          })
          // console.log(that.data.saveBtn,'-----');
        },
        fail: function (err) {
          console.info(err);
        }
      });
    }); //绘制到canvas
  },
  //画矩形，也是整块画布的大小，宽度是屏幕宽度，高度根据内容多少来动态设置。
  drawSquare: function (ctx, height) {
    let that = this;
    ctx.rect(
      0,
      0,
      that.data.boxWidth,
      height
    );
    ctx.setFillStyle("#fff");
    ctx.fill();
  },
  /**
 * 合同
 */
  bindContract:function(e){
    var urls = e.currentTarget.dataset.url;
    urls = this.data.imgDomain+urls;
    wx.showModal({
      title: '温馨提示',
      content: '是否下载！！！',
      success (res) {
        if (res.confirm) {
          wx.downloadFile({
            url: urls, //仅为示例，并非真实的资源
            success (res) {
              var filePath = res.tempFilePath
              wx.openDocument({
                filePath: filePath,
                showMenu:true,
                success(con){ }
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /*
  * 返修退换
  */
  retreatinfo(orderId){
    var that = this;
    orderdetail.getRetreatinfo(orderId,function (content) {
      console.log(content,'------------');
      that.setData({
        retreatList:content
      })
    });
  },
  toPage (e) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url
    })
  },
  /**
   * 复制到剪贴板
   */
  setClipBoard (e) {
    let text = e.currentTarget.dataset.text
    wx.setClipboardData({
      data: text,
      fail (err) {
        console.log(err)
      }
    })
  },
  copyAddress () {
    let consignee = this.data.consignee || {}
    let text = ''
    text += consignee.Name
    if (consignee.Mobile) {
      text += ` ${consignee.Mobile}`
    }
    text += ` ${consignee.Province}`
    text += `${consignee.City}`
    text += `${consignee.Area}`
    if (consignee.Town) {
      text += `${consignee.Town}`
    }
    text += ` ${consignee.Address}`
    wx.setClipboardData({
      data: text,
      fail (err) {
        console.log(err)
      }
    })
  }
})